package com.huike.report.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import com.huike.report.domain.vo.VulnerabilityMapVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.vo.IndexStatisticsVo;
import com.huike.clues.mapper.SysDeptMapper;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.mapper.TbClueMapper;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.utils.SecurityUtils;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.domain.vo.IndexVo;
import com.huike.report.mapper.ReportMapper;
import com.huike.report.service.IReportService;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    private TbContractMapper contractMapper;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Autowired
    private TbClueMapper clueMapper;

    @Autowired
    private TbActivityMapper activityMapper;

    @Autowired
    private TbBusinessMapper businessMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private TbAssignRecordMapper assignRecordMapper;
    
    @Autowired
    private ReportMapper reportMpper;


    @Override
    public IndexVo getIndex(IndexStatisticsVo request) {
        Long deptId= request.getDeptId();
        TbAssignRecord tbAssignRecord=new TbAssignRecord();
        tbAssignRecord.setLatest("1");
        assignRecordMapper.selectAssignRecordList(tbAssignRecord);
        return null;
    }

    @Override
    public List<Map<String, Object>> salesStatisticsForIndex(IndexStatisticsVo request) {
        List<Map<String, Object>> list= contractMapper.contractStatisticsByUser(request);
        for (Map<String, Object> datum : list) {
            Long deptId= (Long) datum.get("dept_id");
            if(deptId!=null){
                SysDept dept= deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return list;
    }

            @Override
        public VulnerabilityMapVo getVulnerabilityMap(IndexStatisticsVo request) {
            List<Map<String, Object>> list = clueMapper.countCluesByStatus(request);
            //将结果封装到数组
            int[] cluesNum=new int[8];//用于存储不同状态的线索数 ,为了可读性强，0下标不使用
            for( Map<String, Object> map :list ){
                for(int x=1;x<=7;x++){
                    if(map.get("status").equals(x+"")){ //已分配
                        cluesNum[x]= ((Long) map.get("num")).intValue();
                    }
                }
            }
            //返回类封装
            VulnerabilityMapVo vo=new VulnerabilityMapVo();
            vo.setCluesNums((cluesNum[1])+cluesNum[2]+cluesNum[3]+cluesNum[4]+cluesNum[6]+cluesNum[7]);//线索数  5为删除
            vo.setEffectiveCluesNums(cluesNum[1]+cluesNum[2]+cluesNum[6]+cluesNum[7]);//有效线索数
            vo.setBusinessNums(cluesNum[6]+cluesNum[7]);//商机数
            vo.setContractNums(cluesNum[7]);//合同数
            return vo;
        }

    /**
     * 线索转化龙虎榜
     * @param request 封装类 IndexStatisticsVo 封装时间
     * @return
     */
    @Override
    public List<Map<String, Object>> clueChangeStatisticsForIndex(IndexStatisticsVo request) {

        int allclues=  clueMapper.countAllClues(request.getBeginCreateTime(),request.getEndCreateTime());
        List<Map<String,Object>> list= clueMapper.countAllClueByUser(request);

        for (Map<String, Object> stringObjectMap : list) {
            System.out.println(stringObjectMap);
        }
        //计算转换率
        for (Map<String, Object> datum : list) {
            Long num= (Long) datum.get("num");
            datum.put("radio",getRadio(allclues,num));
        }
        return list;
    }

    /**
     * 线索转化率
     * @param all
     * @param num
     * @return
     */
    private BigDecimal getRadio(Integer all,Long num) {
        if(all.intValue()==0){
            return new BigDecimal(0);
        }
		BigDecimal numBigDecimal = new BigDecimal(num);
		BigDecimal allBigDecimal = new BigDecimal(all);
		BigDecimal divide = numBigDecimal.divide(allBigDecimal,4,BigDecimal.ROUND_HALF_UP);
		return divide.multiply(new BigDecimal(100));
	}

    /**
     * 商机转换龙虎榜
     * @param request
     * @return
     */
    @Override
    public List<Map<String, Object>> businessChangeStatisticsForIndex(IndexStatisticsVo request) {
        int allBusiness=  businessMapper.countAllBusiness(request.getBeginCreateTime(),request.getEndCreateTime());
        List<Map<String,Object>> list= businessMapper.countAllContractByUser(request);
        for (Map<String, Object> datum : list) {
            Long num= (Long) datum.get("num");
            datum.put("radio",getRadio(allBusiness,num));
        }
        return list;
    }

    /**
     * 页面基础信息的查询
     * @param request
     * @param now
     * @return
     */
    @Override
    public Map<String, Object> getcontractsBasicInfo(IndexStatisticsVo request, String now) {
        Map<String, Object> result = new HashMap<String,Object>();
        //获取当前用户账号
        String username = SecurityUtils.getUsername();
        try {
            //进行优化，开启并发线程
            CompletableFuture<Map<String,Object>> baseData = CompletableFuture.supplyAsync(()->{
                //处理基础数据
                return reportMpper.getBaseData(request, now, username);
            });
            CompletableFuture<Map<String,Object>> todayData = CompletableFuture.supplyAsync(()->{
                //处理今日简报
                return reportMpper.getTodayData(request, now, username);
            });
            CompletableFuture<Map<String,Object>> todoData = CompletableFuture.supplyAsync(()->{
                //处理待办事项
                return reportMpper.getTodoData(request, now, username);
            });
            CompletableFuture
                    .allOf(baseData,
                            todayData,
                            todoData)    //.allof 实现多实例的同时返回
                    .join();   //　join方法是阻塞调用它们的线程（通常为主线程）来获取CompletableFuture异步之后的返回值。
            result.putAll(baseData.get());  //获取返回值
            result.putAll(todayData.get());
            result.putAll(todoData.get());
        }catch (Exception e) {
            return null;
        }
        if(!username.equals("admin")) {
            //不是admin 不能看见待分配商机和待分配线索
            result.put("toallocatedBusinessNum", 0);
            result.put("toallocatedCluesNum", 0);
        }
        return result;
    }

}